package com.cx.web.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cx.pojo.User;
import com.cx.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private UserService service = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        String json = jsonBuilder.toString();
        JSONObject jsonObject = JSON.parseObject(json);

        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");
        String checkCode = jsonObject.getString("checkCode");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        HttpSession session = request.getSession();
        String checkCodeGen = (String) session.getAttribute("checkCodeGen");
        boolean check = checkCodeGen.equalsIgnoreCase(checkCode);
        if(!check){
            response.getWriter().write("v_false");
            return;
        }
        boolean flag = service.register(user);
        if(flag){
            session.setAttribute("register_msg","注册成功，请登录");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
